package main

import (
	"fmt"
)

func main() {
	//创建map赋初值，map[k]v
	m := map[string]string{
		"name":    "ccmouse",
		"course":  "golang",
		"site":    "gitee",
		"quality": "notbad",
	}
	//map的key一定是可比较的，每个字段可比较改结构体也是可比较  ==
	//创建空map
	m2 := make(map[string]int) // m2 == empty map
	//创建空map
	var m3 map[string]int // m3 == nil，go语言nil是可以参与运算的

	fmt.Println("m, m2, m3:")
	fmt.Println(m, m2, m3)

	fmt.Println("Traversing map m")
	// for k := range m {
	// 	fmt.Println(k)
	// }
	// for _, v := range m {
	// 	fmt.Println(v)
	// }

	//for range 类比foreach
	for k, v := range m { //range遍历map,迭代器获取下一个k/v
		fmt.Println(k, v)
	}

	fmt.Println("Getting values")
	courseName := m["course"]
	fmt.Println(`m["course"] =`, courseName)
	if causeName, ok := m["cause"]; ok { //判断map  key是否存在,key不存在时，获得value类型的初始值
		fmt.Println(causeName)
	} else {
		fmt.Println("key 'cause' does not exist")
	}

	fmt.Println("Deleting values")
	name, ok := m["name"]
	fmt.Printf("m[%q] before delete: %q, %v\n",
		"name", name, ok)

	delete(m, "name") //删除key/value
	name, ok = m["name"]
	fmt.Printf("m[%q] after delete: %q, %v\n",
		"name", name, ok)

	//	添加，存在不更新
	if _, ok = m["name"]; !ok {
		m["name"] = "geek"
	}

}
